#!/bin/bash

source /home/shell/util.sh

# 变量区，定义安装变量
read -p "master地址[${host_addr}]：" master_host
master_host=${master_host:-"${host_addr}"}

read -p "master地址[${host_addr}]：" slave_host
slave_host=${slave_host:-"${host_addr}"}

# master_host=$host_addr
# slave_host=192.168.31.50

if [[ "$(ostype)" = "Ubuntu" ]] && [[ ! -f "/etc/apt/sources.list.d/mariadb.list" ]]; then
    apt install -y apt-transport-https
    printInfo "$(ostype)版本安装中";
    curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --os-type=ubuntu --os-version=focal
    apt install -y  maxscale
    cp -f /home/shell/support/MariaDB/maxscale.cnf /etc/maxscale.cnf
elif [[ "$(ostype)" = "CentOS" ]] && [[ ! -f "/etc/yum.repos.d/mariadb.repo" ]]; then
    printInfo "$(ostype)版本安装中";
    curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash
    yum install -y maxscale
    \cp -f /home/shell/support/MariaDB/maxscale.cnf /etc/maxscale.cnf
fi

if [ -f "/usr/bin/maxscale" ]; then
    printSuccess "maxscale安装成功"
else
    printFail "安装失败，请检查后重新运行安装脚本";
    exit;
fi

mysql --login-path=local<<EOF
CREATE USER IF NOT EXISTS 'scalemon'@'%' identified by "123456";
CREATE USER IF NOT EXISTS 'maxscale'@'%' identified by "123456";
grant replication slave, replication client on *.* to 'scalemon'@'%';
grant select on mysql.* to 'maxscale'@'%';
EOF

sed -i "s/server1_addr/"$master_host"/g" /etc/maxscale.cnf
sed -i "s/server2_addr/"$slave_host"/g" /etc/maxscale.cnf


systemctl start maxscale

firewall-addport 3307

printInfo "servers:"
maxctrl list servers
printInfo "services:"
maxctrl list services